import tarfile
import os,sys,shutil


# 递归获取文件夹下所有符合条件的文件路径.
def get_all_filepath(root_dir_path, extension_tag=[], recursive = True):
    """
    Args:
        root_dir_path: 文件根目录.
        extension_tag: 文件后缀名组成的列表, Example: ["jpg", "png", "bmp"]
        如果为空 则获取所有
    Returns:
        特定文件夹下所有符合条件的文件路径.
    """
    def check_endswith(new_path, extension_tag):
        if len(extension_tag) == 0:
            return True
        for s in extension_tag:
            if new_path.lower().endswith(s):
                return True
        return False

    paths = []
    for f in os.listdir(root_dir_path):
        new_path = root_dir_path + os.sep + f
        if os.path.isfile(new_path) and check_endswith(new_path,  extension_tag):
            paths.append(new_path)
        elif os.path.isdir(new_path) and recursive:
            temp_list = get_all_filepath(new_path, extension_tag)
            paths.extend(temp_list)
    return paths


def tar(data_dir, file_list):
    t = tarfile.open(os.path.join(data_dir, "data.tar.gz"), "w:gz")
    for f in file_list:
        t.add(f, arcname=f.replace(data_dir+os.sep, "")  , recursive=True)
    t.close()


def gen_targz(data_dir, file_name="via_region_data.json"):
    files = get_all_filepath(data_dir, ["via_region_data.json", "via_region_data.rec.json"])
    tar(data_dir, files)

def gen_targz_all(data_dir, file_name="via_region_data.json"):
    via_files = get_all_filepath(data_dir, [file_name])
    files = []
    for via_file in via_files:
        fs = get_all_filepath(os.path.dirname(via_file), [])
        files.extend(fs)
    tar(data_dir, files)


if __name__ == "__main__":
    tar_dir = sys.argv[1]
    # gen_targz(tar_dir)
    gen_targz_all(tar_dir)

